﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using BW.Mes.WinForms.Process.Vue;


namespace BW.Mes.WinForms.Process.OperationModel
{
    public partial class OperationDataForm : DevExpress.XtraEditors.XtraForm
    {
        private HttpClient httpClient;
        private string searchOperationName = "";
        private string searchOperationCode = "";
        
        // 添加分页管理器
        private PaginationManager paginationManager;

        public OperationDataForm()
        {
            InitializeComponent();
            InitializeHttpClient();
            InitializeUIControls();
            
            // 初始化分页管理器
            paginationManager = new PaginationManager();
            paginationManager.PageChanged += PaginationManager_PageChanged;
        }

        // 分页事件处理
        private void PaginationManager_PageChanged(object sender, EventArgs e)
        {
            // 页码或页大小改变时重新加载数据
            LoadOperationData();
        }

        private void InitializeHttpClient()
        {
            try
            {
                // Ignore SSL certificate validation for localhost development
                var handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
                };
                httpClient = new HttpClient(handler);
                httpClient.Timeout = TimeSpan.FromSeconds(30); // 增加超时时间
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化HTTP客户端失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void InitializeUIControls()
        {
            try
            {
                // 重命名UI控件，使其更具描述性
                textEdit1.Name = "txtOperationName";
                simpleButton1.Name = "btnSearch";
                labelControl1.Text = "工序名称";

                // 创建列（复选框）
                var checkColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                checkColumn.Name = "colIsSelected";
                checkColumn.FieldName = "IsSelected";
                checkColumn.Caption = "选择";
                checkColumn.Visible = true;
                checkColumn.Width = 50;
                checkColumn.VisibleIndex = 0; // 确保显示在最前面
                checkColumn.OptionsColumn.AllowEdit = true; // 允许编辑
                checkColumn.OptionsColumn.FixedWidth = true;
                var repositoryItemCheckEdit = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit();
                repositoryItemCheckEdit.ValueChecked = true;
                repositoryItemCheckEdit.ValueUnchecked = false;
                repositoryItemCheckEdit.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Standard;
                gridControl1.RepositoryItems.Add(repositoryItemCheckEdit);
                checkColumn.ColumnEdit = repositoryItemCheckEdit;
                gridView1.Columns.Add(checkColumn);
                gridView1.OptionsBehavior.Editable = true;
                gridView1.OptionsSelection.MultiSelect = true;
                gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;

                // 添加基本网格配置
                ConfigureGridViewBasic();

                // Add event handlers
                simpleButton1.Click += BtnSearch_Click;
                this.Load += OperationDataForm_Load;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化控件失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 添加基本网格配置
        private void ConfigureGridViewBasic()
        {
            // 基本网格视图设置
            gridView1.OptionsBehavior.Editable = false;
            gridView1.OptionsView.ShowGroupPanel = false;
            gridView1.OptionsView.ShowIndicator = true;
            gridView1.OptionsView.ShowAutoFilterRow = true;
            
            // 设置表格外观
            gridView1.Appearance.HeaderPanel.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            gridView1.Appearance.Row.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            
            // 启用自动筛选
            gridView1.OptionsCustomization.AllowFilter = true;
            gridView1.OptionsFilter.AllowFilterEditor = true;
            
            // 初始化网格列
            InitializeGridColumns();
        }
        
        // 初始化网格列
        private void InitializeGridColumns()
        {
            // 清除所有现有列
            gridView1.Columns.Clear();
            
            // 添加所需列
            AddGridColumn("Id", "主键", 80);
            AddGridColumn("OperationCode", "工艺编码", 120);
            AddGridColumn("OperationName", "工艺名称", 150);
            AddGridColumn("OperationHead", "负责人", 100);
            AddGridColumn("OperationDepartment", "部门", 100);
            AddGridColumn("OperationStates", "状态", 60);
            AddGridColumn("OperationDesc", "描述", 200);
            AddGridColumn("OperationMaterials", "工艺物料", 200);
            AddGridColumn("Steps", "工序步骤", 200);
            
            // 状态列特殊处理 - 使用文本显示
            var statusColumn = gridView1.Columns["OperationStates"];
            if (statusColumn != null)
            {
                statusColumn.Width = 60;
                statusColumn.OptionsColumn.AllowEdit = false;
                
                // 创建一个文本编辑器作为仓库项
                var textEditRepo = new RepositoryItemTextEdit();
                textEditRepo.ReadOnly = true;
                gridControl1.RepositoryItems.Add(textEditRepo);
                statusColumn.ColumnEdit = textEditRepo;
                
                // 添加值格式化器
                gridView1.CustomColumnDisplayText += (sender, e) => {
                    if (e.Column.FieldName == "OperationStates" && e.Value != null)
                    {
                        if (Convert.ToBoolean(e.Value))
                            e.DisplayText = "启用";
                        else
                            e.DisplayText = "禁用";
                    }
                };
            }
        }
        
        // 辅助方法：添加网格列
        private void AddGridColumn(string fieldName, string caption, int width)
        {
            var column = new DevExpress.XtraGrid.Columns.GridColumn();
            column.Name = fieldName;
            column.FieldName = fieldName;
            column.Caption = caption;
            column.Visible = true;
            column.Width = width;
            column.OptionsColumn.AllowEdit = false;
            gridView1.Columns.Add(column);
        }

        private void OperationDataForm_Load(object sender, EventArgs e)
        {
            try
            {
                // 初始化分页管理器
                paginationManager.Initialize(panelControl2);
                LoadOperationData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"窗体加载失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // 搜索时重置为第一页
                paginationManager.ResetToFirstPage();
                searchOperationName = textEdit1.Text.Trim();
                searchOperationCode = textEdit2.Text.Trim();

                Console.WriteLine($"搜索条件: 工序名称={searchOperationName}, 工序编码={searchOperationCode}");

                // 执行搜索
                LoadOperationData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"搜索操作失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void LoadOperationData()
        {
            try
            {
                // 显示加载中提示
                Cursor = Cursors.WaitCursor;
                
                // 构建API URL - 使用分页管理器的属性
                string url = $"http://120.26.197.100:8022/T5/OperationModel/ShowOperation?PagingSize={paginationManager.PageSize}&PagingIndex={paginationManager.CurrentPage}";
                
                if (!string.IsNullOrEmpty(searchOperationName))
                    url += $"&OperationName={HttpUtility.UrlEncode(searchOperationName)}";
                
                if (!string.IsNullOrEmpty(searchOperationCode))
                    url += $"&OperationCode={HttpUtility.UrlEncode(searchOperationCode)}";

                // 打印URL以便调试
                Console.WriteLine($"API调用: {url}");

                // 发送API请求
                var response = await httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode(); // 确保请求成功
                
                // 获取API响应内容
                var content = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"API响应: {content}");

                // 尝试使用System.Text.Json反序列化
                PagingApiResult<List<OperationModel>> apiResult = null;
                try 
                {
                    // 打印出收到的JSON数据便于诊断
                    Console.WriteLine($"尝试解析JSON: {content}");

                    // 添加更多灵活的反序列化选项
                    var options = new JsonSerializerOptions 
                    { 
                        PropertyNameCaseInsensitive = true,
                        AllowTrailingCommas = true,
                        ReadCommentHandling = System.Text.Json.JsonCommentHandling.Skip,
                        PropertyNamingPolicy = null
                    };
                    
                    // 尝试反序列化
                    apiResult = System.Text.Json.JsonSerializer.Deserialize<PagingApiResult<List<OperationModel>>>(content, options);

                    // 如果数据不为空，输出第一条记录内容进行检查
                    if (apiResult?.pagingdata != null && apiResult.pagingdata.Count > 0)
                    {
                        var firstItem = apiResult.pagingdata[0];
                        Console.WriteLine($"成功解析第一条数据: Id={firstItem.Id}, Name={firstItem.OperationName}");
                    }
                }
                catch(Exception jsonEx)
                {
                    // 详细记录错误信息
                    Console.WriteLine($"JSON解析详细错误: {jsonEx}");
                    MessageBox.Show($"API数据解析失败(System.Text.Json): {jsonEx.Message}\n\n请检查API返回的数据格式是否匹配。", "JSON解析错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    
                    // 尝试使用Newtonsoft.Json作为备选方案
                    try 
                    {
                        apiResult = Newtonsoft.Json.JsonConvert.DeserializeObject<PagingApiResult<List<OperationModel>>>(content);
                        
                        // 如果Newtonsoft成功解析，记录下来
                        Console.WriteLine("成功使用Newtonsoft.Json解析数据");
                        
                        // 检查数据
                        if (apiResult?.pagingdata != null && apiResult.pagingdata.Count > 0)
                        {
                            var firstItem = apiResult.pagingdata[0];
                            Console.WriteLine($"Newtonsoft解析第一条数据: Id={firstItem.Id}, Name={firstItem.OperationName}");
                        }
                    }
                    catch(Exception newtonsoftEx)
                    {
                        Console.WriteLine($"Newtonsoft.Json解析详细错误: {newtonsoftEx}");
                        MessageBox.Show($"API数据解析失败(Newtonsoft.Json): {newtonsoftEx.Message}", "JSON解析错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        
                        // 如果两种解析方法都失败，尝试直接显示内容
                        MessageBox.Show($"原始JSON内容:\n{content.Substring(0, Math.Min(500, content.Length))}...", "原始数据", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

                if (apiResult != null && apiResult.success == 200 && apiResult.pagingdata != null)
                {
                    // 处理分页信息
                    ProcessPagingInformation(response, apiResult);
                    
                    // 绑定数据到网格
                    gridControl1.DataSource = null; // 先清空数据源
                    gridControl1.DataSource = apiResult.pagingdata;
                    
                    // 刷新网格视图
                    gridControl1.RefreshDataSource();
                    gridView1.RefreshData();

                    // 显示加载数据数量
                    Console.WriteLine($"已加载 {apiResult.pagingdata.Count} 条记录");
                }
                else
                {
                    string errorMessage = apiResult != null ? apiResult.message : "未知错误";
                    MessageBox.Show($"获取数据失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (HttpRequestException httpEx)
            {
                MessageBox.Show($"HTTP请求错误: {httpEx.Message}\n请确认API服务是否启动并可访问。", "网络错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载工艺数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        private void ProcessPagingInformation(HttpResponseMessage response, PagingApiResult<List<OperationModel>> apiResult)
        {
            try
            {
                // 从响应头获取总记录数
                string totalHeader = "";
                if (response.Headers.TryGetValues("X-Total-Count", out var values))
                {
                    totalHeader = values.FirstOrDefault();
                }

                int totalRecords = 0;
                
                if (!string.IsNullOrEmpty(totalHeader) && int.TryParse(totalHeader, out int total))
                {
                    // 如果响应头中有总记录数，直接使用
                    totalRecords = total;
                }
                else if (apiResult.totalCount > 0)
                {
                    // 如果API响应中包含总记录数，使用它
                    totalRecords = apiResult.totalCount;
                    Console.WriteLine($"使用API返回的总记录数: {totalRecords}");
                }
                else if (apiResult.success == 200)
                {
                    // 备选方案：根据页面结果估算总记录数
                    var list = apiResult.pagingdata ?? new List<OperationModel>();
                    
                    // 估算总记录数
                    if (list.Count < paginationManager.PageSize && paginationManager.CurrentPage > 1)
                    {
                        // 当前页小于页大小，说明这是最后一页
                        totalRecords = (paginationManager.CurrentPage - 1) * paginationManager.PageSize + list.Count;
                        Console.WriteLine($"估算总记录数(最后一页): {totalRecords}");
                    }
                    else if (list.Count < paginationManager.PageSize)
                    {
                        // 第一页且记录数小于页大小
                        totalRecords = list.Count;
                        Console.WriteLine($"估算总记录数(第一页): {totalRecords}");
                    }
                    else
                    {
                        // 如果等于页大小，至少还有这么多记录
                        totalRecords = Math.Max(totalRecords, paginationManager.CurrentPage * paginationManager.PageSize);
                        Console.WriteLine($"估算总记录数(满页): {totalRecords}");
                    }
                }
                
                // 更新分页管理器中的数据
                paginationManager.UpdatePagingData(totalRecords);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"处理分页信息失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public class OperationModel
        {
            public bool IsSelected { get; set; }
           
            /// <summary>
            /// 主键
            /// </summary>
            public long Id { get; set; }
            /// <summary>
            /// 工艺编码
            /// </summary>
            public string OperationCode { get; set; }

            /// <summary>
            /// 工艺名称
            /// </summary>
            public string OperationName { get; set; }

            /// <summary>
            /// 工艺负责人
            /// </summary>
            public string OperationHead { get; set; }           

            /// <summary>
            /// 工艺状态
            /// </summary>
            public bool OperationStates { get; set; }

            /// <summary>
            /// 工艺描述
            /// </summary>
            public string OperationDesc { get; set; }

            /// <summary>
            /// 工艺物料
            /// </summary>
            public string OperationMaterials { get; set; }

            /// <summary>
            /// 工序步骤(JSON格式)
            /// </summary>
            public string Steps { get; set; }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            // 创建添加窗体
            var addForm = new AddOperationForm();
            
            // 订阅添加完成事件
            addForm.OperationAdded += AddForm_OperationAdded;
          
            // 显示对话框，以模态方式打开
            addForm.ShowDialog();
        }
        
        // 添加事件处理方法
        private void AddForm_OperationAdded(object sender, EventArgs e)
        {
            // 当添加操作完成后刷新数据
            LoadOperationData();
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            // 获取选中的行
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请先选择要分配流程的工序！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }            
            // 获取选中的第一个工序ID
            if (selectedRows.Length > 0)
            {
                int rowHandle = selectedRows[0];
                if (rowHandle >= 0)
                {
                    var model = gridView1.GetRow(rowHandle) as OperationModel;
                    if (model != null)
                    {
                        string selectedId = model.Id.ToString();
                        
                        // 显示加载中指示器
                        Cursor = Cursors.WaitCursor;
                        
                        try
                        {
                            // 使用新的方法打开工序流程分配的Vue页面，只传递单个ID
                            var form = Vue.VuePageManager.OpenProcessAssignmentPage(selectedId, "工序流程分配");
                            
                            // 如果成功打开Vue页面，添加事件处理
                            if (form != null)
                            {
                                // 处理对话框关闭事件
                                form.FormClosed += (s, args) => {
                                    // 恢复光标
                                    Cursor = Cursors.Default;
                                    
                                    // 获取对话框结果
                                    if (((Form)s).DialogResult == DialogResult.OK)
                                    {
                                        // 如果是成功分配流程（DialogResult.OK）
                                        XtraMessageBox.Show("成功为工序分配了流程。", 
                                            "分配成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    }
                                    
                                    // 不管结果如何，都刷新数据
                                    LoadOperationData();
                                };
                            }
                            else
                            {
                                // 如果打开失败，恢复光标
                                Cursor = Cursors.Default;
                            }
                        }
                        catch (Exception ex)
                        {
                            // 发生错误时恢复光标并显示错误
                            Cursor = Cursors.Default;
                            XtraMessageBox.Show($"打开工序流程分配页面时发生错误: {ex.Message}", 
                                "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }

        // BtnSearch_Click方法，使用simpleButton1_Click的实现
        private void BtnSearch_Click(object sender, EventArgs e)
        {
            simpleButton1_Click(sender, e);
        }
    }
}